package com.jnu.myaccount_drawer.data;
import android.annotation.SuppressLint;
import android.content.Context;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class DataBank {

    public static final String DATA_FILE_NAME = "data";
    private final Context context;
    private List<AccountType> accountType;

    public DataBank(Context context) {
        this.context=context;
    }

    //获取当天日期
    Calendar calendar = Calendar.getInstance();
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String stringDate = simpleDateFormat.format(calendar.getTime());

    public List<AccountType> loadData() {
        accountType = new ArrayList<AccountType>();//防止一开始没有数据
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(context.openFileInput(DATA_FILE_NAME));
            accountType = (ArrayList<AccountType>) objectInputStream.readObject();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return accountType;
    }

    public void saveData() {
        ObjectOutputStream objectOutputStream=null;
        try{
            objectOutputStream = new ObjectOutputStream(context.openFileOutput(DATA_FILE_NAME, Context.MODE_PRIVATE));
            objectOutputStream.writeObject(accountType);
        }
        catch(IOException e){
            e.printStackTrace();
        }
        finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

